package br.com.gaspar.academia.bo;


import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import br.com.gaspar.academia.bo.iface.IContatoBO;
import br.com.gaspar.academia.dao.iface.IProjetoDAO;
import br.com.gaspar.academia.modelo.Contato;
import br.com.gaspar.framework.modelo.BaseBO;
import br.com.gaspar.framework.persistencia.IBaseDAO;
import br.com.gaspar.utils.exception.BaseException;

@Stateless
@Local(IContatoBO.class)
public class ContatoBO extends BaseBO<Contato> implements IContatoBO {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3883932252251097740L;
	
	@EJB
	private IProjetoDAO<Contato> dao;
	
	@Resource(name="mail/gmailResource")
	private Session sessaoEmail;
	
	@Override
	public IBaseDAO<Contato> getDAOPadrao() {
		return this.dao;
	}
	
	@Override
	protected void gravarApos(Contato entidade) throws BaseException {
		try {
			enviarEmail(entidade);
		} catch (AddressException e) {
			throw new BaseException("Erro ao enviar e-mail");
		} catch (MessagingException e) {
			throw new BaseException("Erro ao enviar e-mail");
		}
	}

	public void enviarEmail(Contato contato) throws AddressException, MessagingException{
	     Message message = new MimeMessage(sessaoEmail);//leobluma
	     message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("gasparkf@gmail.com", false));
	     message.setFrom(new InternetAddress(contato.getEmail()));
	     message.setSubject(contato.getAssunto());
	     message.setText(contato.getMensagem());
	     message.setHeader("X-Mailer", "My Mailer");
	     message.setSentDate(new Date());
	     
	     Transport.send(message);
		
	}

}
